use Net::SNMP;

sub ip2hex{
    my ($ip) = @_;
    my $hex = "";
    foreach my $octet (split(/\./, $ip, 4)) {
        $hex .= sprintf("%02x",$octet);
    }
    return $hex;
}

sub get {
    my ($hostname, $community, $oid) = @_;
    my ($session, $error) = Net::SNMP->session(
	    -hostname => $hostname,
	    -community => $community,
	    -timeout => 1,
	    -version => '2',
	);
	
    my $res = $session->get_request(-varbindlist => [$oid]);
    if(!defined $res){
	print $session->error();
    }

    $session->close();
    return $res->{$oid};
}

sub get_next {
    my ($hostname, $community, $oid) = @_;
    my ($session, $error) = Net::SNMP->session(
	    -hostname => $hostname,
	    -community => $community,
	    -timeout => 1,
	    -version => '2',
	);
	
    my $res = $session->get_next_request(-varbindlist => [$oid]);
    if(!defined $res){
	print $session->error();
    }

    $session->close();
    my ($key, $value) = each(%$res);
    return {key=>$key, value=>$value};
}

sub get_tnext{
    my ($hostname, $community, $oid) = @_;
    my $res;
    my $r;
    my $i = 0;
    $r->{key} = $oid;
    select(STDOUT); # default
    $| = 1;
    while(1){
	$r = ::get_next($hostname, $community, $r->{key});
	if(index($r->{key}, $oid) != 0) { last };
	$res->{$r->{key}} = $r->{value};
	select(undef, undef, undef, 0.02); # default
	printf "\rGetting table $oid : %d entries read", $i++;
    }
    printf "\n";
    return  $res;
}

sub get_table{
    my ($hostname, $community, $oid) = @_;
    my ($session, $error) = Net::SNMP->session(
	    -hostname => $hostname,
	    -community => $community,
	    -timeout => 60,
	    -version => '2',
	);
	
    my $res = $session->get_entries(-columns => $oid);
    if(!defined $res){
	print $session->error();
    }

    $session->close();
    return $res;
}

sub get_table1{
    my ($hostname, $community, $oid) = @_;
    my ($session, $error) = Net::SNMP->session(
	    -hostname => $hostname,
	    -community => $community,
	    -timeout => 60,
	    -version => '2',
	);
	
    my $res = $session->get_table(-columns => $oid, -maxrepetitions => 10);
    if(!defined $res){
	print $session->error();
    }

    $session->close();
    return $res;
}

1;
